import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import { Row, Col, Input, Button, Table, Card, message, Icon, Pagination, Form, Select, DatePicker } from 'antd';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import IntroduceRow from '@/pages/Home/IntroduceRow';
import ProportionSales from '@/pages/Home/ProportionSales';
import HotQuestionTable from '@/pages/Home/hotQuestionTable';
const { RangePicker } = DatePicker;
import moment from 'moment';

@connect(({ home, loading }) => ({
  home,
  loading: loading.effects['home/fetch'],
}))
class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      queryData: {
        applicationId: '0',
        fromDate: '',
        toDate: '',
        trigger: '',
      },
      robotList: [],
      loading: true,
      visitData: null,
      hotLoading: false,
      visitItem: [],
      questionItem: [],
      hotQuestion: [],
      questionTypeItem: [],
      feedBackItem: []
    }
  }

  componentWillMount() {
    const fromDate = moment().subtract("1", 'days').format('YYYY-MM-DD');
    const toDate = moment().subtract("1", 'days').format('YYYY-MM-DD');
    let { queryData } = this.state;
    queryData.fromDate = fromDate;
    queryData.toDate = toDate;
    this.setState({ queryData })
  }

  componentDidMount() {
    this.getRobot();
    this.getStatInfo();
    this.getHotQuestion();
  }

  /**
   * 获取所有机器人（作为筛选条件）
   */
  getRobot = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'home/fetchRobotList',
      payload: { current: 1, size: 999999 },
      callback: res => {
        this.setState({ robotList: res })
      },
    })
  }

  /**
   * 获取统计信息
   */
  getStatInfo = () => {
    const { dispatch } = this.props;
    const { queryData } = this.state;
    this.setState({ loading: true }, () => {
      dispatch({
        type: 'home/fetchStatInfo',
        payload: queryData,
        callback: res => {
          //访客数量-判断是否全为0
          const visitItem = res.visit.spread.filter(item => item.y != 0);
          //问答数量-判断是否全为0
          const questionItem = res.visit.spread.filter(item => item.y != 0);
          //问题类型分布-判断是否全为0
          const questionTypeItem = res.questionType.filter(item => item.y != 0);
          //用户反馈分布-判断是否全为0
          const feedBackItem = res.feedBack.filter(item => item.y != 0);

          // if(questionTypeItem.length === 0){
          //   res.questionType.push({ "x": "暂无数据","y": 100})
          // }
          // if(feedBackItem.length === 0){
          //   res.feedBack.push({ "x": "暂无数据","y": 100})
          // }

          this.setState({
            loading: false,
            visitData: res,
            visitItem,
            questionItem,
            questionTypeItem,
            feedBackItem
          })
        },
      })
    })
  }

  /**
   * 获取热点问题
   */
  getHotQuestion = () => {
    const { dispatch } = this.props;
    const { queryData } = this.state;
    this.setState({ hotLoading: true }, () => {
      dispatch({
        type: 'home/fetchHotQuestion',
        payload: queryData,
        callback: res => {
          this.setState({ hotQuestion: res, hotLoading: false })
        },
      })
    })
  }

  /**
   * 根据条件查询
   * @returns {*}
   */
  queryByConditions = () => {
    const { form } = this.props;
    let queryData = form.getFieldsValue();
    queryData.fromDate = queryData.time[0].format('YYYY-MM-DD');
    queryData.toDate = queryData.time[1].format('YYYY-MM-DD');
    delete queryData.time;
    this.setState({ queryData }, () => {
      this.getStatInfo();
      this.getHotQuestion();
    })
  }

  render() {
    const { robotList, loading, visitData, hotLoading, visitItem, questionItem, hotQuestion, questionTypeItem, feedBackItem } = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <GridContent>
        <Row>
          <Col span={24} style={{ textAlign: 'right', marginBottom: 10 }}>
            <Form layout={'inline'}>
              <Form.Item>
                {
                  getFieldDecorator('applicationId', { initialValue: '0' })(
                    <Select placeholder={'请选择应用'} style={{ width: 200 }}>
                      <Select.Option value={'0'}>全部应用</Select.Option>
                      {
                        robotList.map(item => {
                          return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                        })
                      }
                    </Select>
                  )
                }
              </Form.Item>
              <Form.Item style={{ textAlign: 'center' }}>
                {
                  getFieldDecorator('time', {
                    initialValue: [moment().subtract('1', 'days'), moment().subtract('1', 'days')]
                  })(
                    <RangePicker allowClear={false} style={{ width: '250px' }} />
                  )
                }
              </Form.Item>
              <Form.Item>
                {
                  getFieldDecorator('trigger', { initialValue: '' })(
                    <Select placeholder={'请选择触发方式'} style={{ width: 200 }}>
                      <Select.Option value={''}>全部触发方式</Select.Option>
                      <Select.Option value={1}>点击触发</Select.Option>
                      <Select.Option value={2}>输入触发</Select.Option>
                    </Select>
                  )
                }
              </Form.Item>
              <Form.Item>
                <Button type={'primary'} onClick={this.queryByConditions}>查看</Button>
              </Form.Item>
            </Form>
          </Col>
        </Row>
        <IntroduceRow loading={loading} visitData={visitData} visitItem={visitItem} questionItem={questionItem} />
        <Row gutter={24}>
          <Col xl={12} lg={24} md={24} sm={24} xs={24}>
            <ProportionSales
              loading={loading}
              dataOfQuestionType={visitData ? visitData.questionType : []}
              dataOfFeedBack={visitData ? visitData.feedBack : []}
            />
          </Col>
          <Col xl={12} lg={24} md={24} sm={24} xs={24}>
            <HotQuestionTable loading={hotLoading} list={hotQuestion} questionTypeItem={questionTypeItem} feedBackItem={feedBackItem} />
          </Col>
        </Row>
      </GridContent>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(Home));
